﻿using System;
using System.IO;
using SAM.Framework.ILicence;
using SAM.Framework.ILicence.Models;
using Newtonsoft.Json;

namespace SAM.Framework.LicenceRepositories
{
    public class TextRepository : ILicenceRepository
    {
        private string codePath;
        private string licencePath;

        public TextRepository()
        {
            codePath = Path.Combine(Directory.GetCurrentDirectory(), "code.txt");
            licencePath = Path.Combine(Directory.GetCurrentDirectory(), "licence.txt");
        }

        public T ReadAuthorizationInfo<T>() where T: AuthorizationInfo
        {
            return this.Deserialize<T>(this.licencePath);
        }

        public T ReadMachineCodeInfo<T>() where T: MachineCodeInfo
        {
            return this.Deserialize<T>(this.codePath);
        }

        public bool Save(AuthorizationInfo authorizationInfo)
        {
            this.Serialize<AuthorizationInfo>(authorizationInfo, licencePath);
            return true;
        }

        public bool Save(MachineCodeInfo machineCodeInfo)
        {
            this.Serialize<MachineCodeInfo>(machineCodeInfo, this.codePath);
            return true;
        }

        private void Serialize<T>(T obj, string filePath)
        {
            string content = JsonConvert.SerializeObject(obj);
            System.IO.File.WriteAllText(filePath, content);
        }
        private T Deserialize<T>(string filePath)
        {
            T retObj = default(T);
            if (System.IO.File.Exists(filePath)) {
                string content = System.IO.File.ReadAllText(filePath);
                retObj = JsonConvert.DeserializeObject<T>(content);
            }

            return retObj;
        }
    }
}
